<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserLoginRequest;
use App\Http\Requests\UserRegRequest;
use App\Http\Requests\UserResetRequest;
use App\Http\Requests\UserRetrieveRequest;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

class LoginController extends Controller
{
    /**
     * Create user
     *
     * @param  [string] name
     * @param  [string] email
     * @param  [string] password
     * @param  [string] password_confirmation
     * @return [string] message
     */
    public function register(UserRegRequest $request)
    {
        //获取UniPush ClientId
        $clientId = request()->header('clientId');

        //校验验证码
        $result = checkSmsCode($request->email,$request->code,1);
        if ($result['code'] != 200){
            return echoJson($result['msg'],$result['code']);
        }

        $user = new User([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
            'client_id' => $clientId??'',
        ]);

        $user->save();

        $tokenResult = $user->createToken(env('PASSPORT_TOKEN'));
        $token = $tokenResult->token;

        $token->save();

        return jsonSuccessData([
            'access_token' => $tokenResult->accessToken,
            'userInfo'=> $user
        ]);
    }

    /**
     * Login user and create token
     *
     * @param  [string] email
     * @param  [string] password
     * @param  [boolean] remember_me
     * @return [string] access_token
     * @return [string] token_type
     * @return [string] expires_at
     */
    public function login(UserLoginRequest $request)
    {

        //获取UniPush ClientId
        $clientId = request()->header('clientId');

        $credentials = request(['email', 'password']);

        if(!Auth::attempt($credentials))
            return echoJson('账号/密码错误',1001);

        $user = $request->user();

        if (!empty($clientId)){
            $user->update([
                'client_id' => $clientId
            ]);
        }

        $tokenResult = $user->createToken(env('PASSPORT_TOKEN'));
        $token = $tokenResult->token;

        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);

        $token->save();

        return echoJson('success',200,[
            'access_token' => $tokenResult->accessToken,
//            'token_type' => 'Bearer',
//            'expires_at' => Carbon::parse(
//                $tokenResult->token->expires_at
//            )->toDateTimeString(),
            'userInfo'=>$request->user()
        ]);
    }

    /**
     * Logout user (Revoke the token)
     *
     * @return [string] message
     */
    public function logout(Request $request)
    {
        $request->user()->token()->revoke();

        return echoJson('退出登陆成功',200);
    }

    /**
     * 重制密码
     * @param  string oldPassword
     * @param  string password
     * @param  string password_confirmation
     * @return string
     * */
    public function resetPassword(UserResetRequest $request)
    {

        $user = $request->user();

        $credentials = [
            'email' => $user->email,
            'password' =>$request->oldPassword
        ];
        if(Auth::guard('users')->once($credentials)) {

            $user->update([
                'password' => bcrypt($request->password)
            ]);

            $tokenResult = $user->createToken(env('PASSPORT_TOKEN'));
            $token = $tokenResult->token;

            $token->save();

            return jsonSuccessData([
                'access_token' => $tokenResult->accessToken,
                'userInfo'=>$request->user()
            ]);
        } else {
            return echoJson('账号/密码错误',1001);
        }

    }


    /**
     * 找回密码
     * @param  string email
     * @param  string code
     * @param  string password
     * @param  string password_confirmation
     * @return string
     * */
    public function retrievePassword(UserRetrieveRequest $request)
    {

        //获取UniPush ClientId
        $clientId = request()->header('clientId');

        $key = config('cacheKey.codeToken').$request->email;
        $token = Redis::get($key);
        if ($token != $request->token){
            return echoJson('该token无效',1006);
        }

        $update = [];
        $update['password'] = bcrypt($request->password);
        if (!empty($clientId)){
            $update['client_id'] = $clientId;
        }
        $result = User::where('email',$request->email)->update($update);

        if ($result){

            $credentials = request(['email', 'password']);

            if(Auth::attempt($credentials)) {

                $user = $request->user();

                $tokenResult = $user->createToken(env('PASSPORT_TOKEN'));
                $token = $tokenResult->token;

                $token->save();

                //删除缓存
                Redis::del($key);

                return jsonSuccessData([
                    'access_token' => $tokenResult->accessToken,
                    'userInfo'=>$request->user()
                ]);

            } else {
                return jsonErrorData('SYSTEM_ERROR');
            }
        }else {
            return echoJson('修改密码错误',500);
        }

    }

}